﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static string file = "c:\\companydic.xml";
        static List<Company> companies = new List<Company>();
        static string currentURL = null;

        static void Main(string[] args)
        {
            //GetCompanyList();
            InitGeoInfo();
        }

        private static void InitGeoInfo()
        {
            string geocodeUrlFormat = "http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false";
            using (XmlReader reader = new XmlTextReader(file))
            {
                XDocument doc = XDocument.Load(reader);
                foreach (XElement element in doc.Descendants("Company"))
                {
                    var name = element.Element("Name").Value;
                    var add = element.Element("Address").Value;

                    string latlng = GoogleMapHelper.GetLatLngByAddress(add);
                    element.Add(new XElement("LatLng", latlng));
                }
                string haha = doc.ToString();
            }
        }

        private static void GetCompanyList()
        {
            Thread t = new Thread(new ThreadStart(Output));
            t.Start();

            List<string> urls = new List<string>();
            for (int i = 3590; i <= 6930; i += 10)
            {
                urls.Add(string.Format("http://www.iteer.net/modules/xdirectory/viewcat.php?cid=203&min={0}&orderby=hitsD&show=10", i));
            }

            foreach (string url in urls)
            {
                try
                {
                    currentURL = url;
                    WebRequest request = WebRequest.Create(url);
                    using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("GB2312")))
                    {
                        string html = reader.ReadToEnd();
                        var comList = HtmlAnalyzer.Parse(html);
                        companies.AddRange(comList);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                    continue;
                }
            }
        }

        static void Output()
        {
            bool hasWait = false;
            while (true)
            {
                if (companies.Count < 100 && !hasWait)
                {
                    Thread.Sleep(20000);
                    hasWait = true;
                    continue;
                }

                hasWait = false;
                List<Company> temp = new List<Company>();
                temp.AddRange(companies);
                companies.Clear();

                bool isHead = false;
                if (!File.Exists(file))
                {
                    isHead = true;
                }

                using (FileStream stream = new FileStream(file, isHead ? FileMode.CreateNew : FileMode.Append, FileAccess.Write))
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        if (isHead)
                            writer.WriteLine("<Root>");
                        StringBuilder sb = new StringBuilder();
                        foreach (var c in temp)
                        {
                            sb.AppendFormat("<Company><Name>{0}</Name><Address>{1}</Address></Company>\r\n", c.Name, c.Address);
                        }
                        writer.WriteLine(sb.ToString());

                        if (temp.Count == 0)
                        {
                            writer.WriteLine("</Root>");
                            writer.WriteLine(currentURL);
                            break;
                        }
                    }
                }
            }
        }

        static void Output(List<Company> companies)
        {
            XElement root = new XElement("Root");
            foreach (var c in companies)
            {
                root.Add(new XElement("Company", new XElement("Name", c.Name), new XElement("Address", c.Address)));
            }
            string haha = root.ToString();
        }
    }
}
